#include "Effect.h"

Effect::Effect()
{

}
Effect::~Effect()
{
	ClearSections();
	program.Dispose();
}

void Effect::Init(EffectData & data)
{
	program.Bind();

	if(data.fs.empty == false)
	{
		Shader vs(VERTEX);
		vs.LoadFromString(data.vs.c_str());

		if(data.vsPP.empty() == false)
		{
			vs.Compile(data.vsPP.c_str());
		}
		else 
		{
			vs.Compile();
		}

		program.AttachShader(vs.GetGLShader());
		vs.Dispose();
	}

	if(data.fs.empty() == false)
	{
		Shader fs(PIXEL);
		fs.LoadFromString(data.fs.c_str());

		if(data.fsPP.empty() == false)
		{
			fs.Compile(data.vsPP.c_str());
		}
		else 
		{
			fs.Compile();
		}

		program.AttachShader(fs.GetGLShader());
	}

	program.LinkShaders();

	transorms.Init(&program);

	program.Unbind();


}

void Effect::Apply()
{
	program.Bind();
}

void Effect::AddSection(EngineFeature featureID,IEffectSection * section)
{
	sectionsMap[featureID] = section;
	sectionsMemoryHandler.push_back(section);
	section->Init(&program);
}

IEffectSection * Effect::GetSection(EngineFeature featureID)
{
	if(sectionsMap.count(featureID) == 1)
		return sectionsMap[featureID];
	else return nullptr;
}

void Effect::ClearSections()
{
	for(std::vector<IEffectSection*>::iterator it = sectionsMemoryHandler.begin();it != sectionsMemoryHandler.end();++it)
	{
		if((*it) != nullptr)
			delete (*it);
	}

	sectionsMap.clear();
}

TransformationSection * Effect::GetTransformSection()
{
	return &transorms;
}